/**
 * 网络连接
 */

var AutoReconnectWsRpcClient = require('AutoReconnectWsRpcClient')
var EventEmitter = require('EventEmitter')
var Config = require('Config')
var LoginManager = require('LoginManager')
var UserManager = require('UserManager')

class NetworkManager {
    /**
     * 连接并认证账号是否正确
     *
     * @return {[type]} [description]
     */
    static connectAndAuthToHall () {
        if (NetworkManager.gHallServer === null) {
            NetworkManager.gHallServer = new AutoReconnectWsRpcClient()
            NetworkManager.gHallServer.connect(NetworkManager.hallWss)
            NetworkManager.gHallServer.onClose(() => {
                // 连接中断
                NetworkManager.gHallServerIsLogin = false
                NetworkManager.hallEvents.emit('closeFormHall')
                NetworkManager.connectAndAuthToHall()
            })
        }

        NetworkManager.gHallServer.onReady((service) => {
            var $token = cc.sys.localStorage.getItem('__TOKEN__')

            service.proxy.login($token, (data) => {
                if (data.ok && data.code === 200) {
                    NetworkManager.gHallServerIsLogin = true
                    cc.sys.localStorage.setItem('__PLAYER_BASE_INFO__', data.datas)
                    NetworkManager.hallEvents.emit('loginToHall')
                } else {
                    cc.director.loadScene('login')
                }
            })
        })
    }

    /**
     * 连接成功，回调函数
     *
     * @param  {Function} cb [description]
     * @return {[type]}      [description]
     */
    static onConnectedToHall (cb) {
        if (NetworkManager.gHallServerIsLogin) {
            cb(NetworkManager.gHallServer)
            return;
        }
        NetworkManager.hallEvents.on('loginToHall', cb)
    }

    /**
     * 关闭连接
     *
     * @param  {Function} cb [description]
     * @return {[type]}      [description]
     */
    static offConnectedToHall (cb) {
        NetworkManager.hallEvents.off(cb)
    }

    /**
     * 中断
     *
     * @param  {Function} cb [description]
     * @return {[type]}      [description]
     */
    static onCloseFormHall (cb) {
        NetworkManager.hallEvents.on('closeFormHall', cb)
    }

    /**
     * 关闭大厅连接
     *
     * @param  {Function} cb [description]
     * @return {[type]} [description]
     */
    static offCloseFormHall (cb) {
        NetworkManager.hallEvents.off(cb)
    }

    /**
     * 清除大厅连接
     *
     * @return {[type]} [description]
     */
    static clearHallService () {
        NetworkManager.hallEvents = new EventEmitter()
        NetworkManager.gHallServerIsLogin = false
        if (NetworkManager.gHallServer) {
            NetworkManager.gHallServer.clear()
            NetworkManager.gHallServer = null
        }
    }

    /**
     * 更新用户信息
     *
     * @return {[type]} [description]
     */
    static updateUserInfo () {
        var $token = cc.sys.localStorage.getItem('__TOKEN__')
        NetworkManager.gHallServer.proxy.getUserInfo($token, (data) => {
            if (data.ok && data.code === 200) {
                NetworkManager.gHallServerIsLogin = true
                cc.sys.localStorage.setItem('__PLAYER_BASE_INFO__', data.datas)
            } else {
                cc.director.loadScene('login')
            }
        })
    }

    /**
     * 删除邮件
     *
     * @param  {[type]} id [description]
     * @return {[type]}    [description]
     */
    static doEmailDeleted (id) {
        var $token = cc.sys.localStorage.getItem('__TOKEN__')
        NetworkManager.onConnectedToHall( (hallService) => {
            hallService.proxy.deletedEmail($token, id, (data) => {
                console.log('删除:', data)
            })
        })
    }

    /**
     * 已读邮件
     *
     * @param  {[type]} id [description]
     * @return {[type]}    [description]
     */
    static doEmailRead (id) {
        var $token = cc.sys.localStorage.getItem('__TOKEN__')
        NetworkManager.onConnectedToHall( (hallService) => {
            hallService.proxy.readEmail($token, id, (data) => {
                console.log('已读:', data)
            })
        })
    }

    // *************************************************** //
    //                   游戏服务网络                        //
    // *************************************************** //
    /**
     * 连接并认证游戏服务器
     *
     * @param  {Function} cb [description]
     * @return {[type]}      [description]
     */
    static connectAndAuthToGame () {
        if (NetworkManager.gGameServer === null) {
            NetworkManager.gGameServer = new AutoReconnectWsRpcClient()
            NetworkManager.gGameServer.connect(NetworkManager.gameWss)
            NetworkManager.gGameServer.onClose(() => {
                // 连接中断
                NetworkManager.gGameServerIsLogin = false
                NetworkManager.gameEvents.emit('closeFormHall')
                NetworkManager.connectAndAuthToGame()
            })
        }

        NetworkManager.gGameServer.onReady((service) => {
            var token = cc.sys.localStorage.getItem('__TOKEN__')

            service.proxy.login(token, (data) => {
                if (data.ok && data.code === 200) {
                    NetworkManager.gGameServerIsLogin = true
                    cc.sys.localStorage.setItem('__PLAYER_BASE_INFO__', data.datas)

                    UserManager.token = token
                    UserManager.loginToGameData = JSON.parse(data.datas)
                    NetworkManager.gameEvents.emit('loginToGame', service)
                } else {
                    cc.director.loadScene('login')
                }
            })
        })
    }

    /**
     * 游戏连接成功，回调函数
     *
     * @param  {Function} cb [description]
     * @return {[type]}      [description]
     */
    static onConnectedToGame (cb) {
        if (NetworkManager.gGameServerIsLogin) {
            cb(NetworkManager.gGameServer)
            return;
        }
        NetworkManager.gameEvents.on('loginToGame', cb)
    }

    /**
     * 关闭连接
     *
     * @param  {Function} cb [description]
     * @return {[type]}      [description]
     */
    static offConnectedToGame (cb) {
        NetworkManager.gameEvents.off(cb)
    }

    static onCloseFormGame (cb) {
        NetworkManager.gameEvents.on('closeFormHall', cb)
    }

    /**
     * 关闭游戏连接
     *
     * @param  {Function} cb [description]
     * @return {[type]} [description]
     */
    static offCloseFormGame (cb) {
        NetworkManager.gameEvents.off(cb)
    }

    /**
     * 清除游戏连接
     *
     * @return {[type]} [description]
     */
    static clearGameService () {
        NetworkManager.gameEvents = new EventEmitter()
        NetworkManager.gGameServerIsLogin = false
        if (NetworkManager.gGameServer) {
            NetworkManager.gGameServer.clear()
            NetworkManager.gGameServer = null
        }
    }
}

/**
 * 连接大厅服务
 *
 * @type {[type]}
 */
NetworkManager.gHallServer = null

/**
 * 连接大厅状态
 *
 * @type {Boolean}
 */
NetworkManager.gHallServerIsLogin = false

/**
 * 大厅的地址
 *
 * @type {[type]}
 */
NetworkManager.hallWss = Config.hallWss


/**
 * 大厅事件定义
 *
 * @type {EventEmitter}
 */
NetworkManager.hallEvents = new EventEmitter()

/**
 * 连接游戏服务
 *
 * @type {[type]}
 */
NetworkManager.gGameServer = null

/**
 * 连接游戏状态
 *
 * @type {Boolean}
 */
NetworkManager.gGameServerIsLogin = false

/**
 * 游戏地址
 *
 * @type {[type]}
 */
NetworkManager.gameWss = Config.gameWss

/**
 * 游戏事件定义
 *
 * @type {EventEmitter}
 */
NetworkManager.gameEvents = new EventEmitter()

module.exports = NetworkManager
